#include "thread_binder.h"
#ifdef WIN32
#include <windows.h>

DWORD WINAPI Wrapper(LPVOID lpThreadParameter)
{
    ThreadWrapperArg* wrapper_arg = (ThreadWrapperArg*)lpThreadParameter;
    wrapper_arg->start_address(wrapper_arg->arg);
    delete wrapper_arg;
    return 0;
}

long CThreadBinder::MakeThread(unsigned long* thread_id, void* (*start_address)(void*), void* arg)
{
    ThreadWrapperArg* wrapper_arg = new ThreadWrapperArg;
    wrapper_arg->start_address = start_address;
    wrapper_arg->arg = arg;
    HANDLE handle = CreateThread(NULL, 0, Wrapper, wrapper_arg, 0, thread_id);
    long err = 0;
    if (handle == 0)
    {
        err = GetLastError();
    }
    *thread_id = (unsigned long)handle;
    return err;
}

void CThreadBinder::WaitFor(unsigned long thread_id)
{
    WaitForSingleObject((HANDLE)thread_id, INFINITE);
}

void CThreadBinder::ExitFromThread(unsigned long result)
{
    ExitThread(result);
}

void CThreadBinder::CleanThread(unsigned long handle)
{
    CloseHandle((HANDLE)handle);
}

#endif